package personal.wang.boss;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import personal.wang.config.DataMockYamlReader;
import personal.wang.handler.EventHandler;
import personal.wang.manager.RecordGeneratorManager;
import personal.wang.manager.WorkerManager;
import personal.wang.manager.ZookeeperManager;
import personal.wang.message.MessageDecoder;
import personal.wang.message.MessageEncoder;
import personal.wang.util.MessageUtil;
import personal.wang.util.ParameterUtil;

import java.util.Properties;

import static personal.wang.constant.ConstantVar.NETTY_BOSS_PORT;
import static personal.wang.constant.ConstantVar.YAML_FILE_PATH;

/**
 * @className: Boss
 * @Description:
 * @Author: wangyifei
 * @Date: 2025/2/14 10:45
 */
public class Boss {
    private static final Logger logger = LoggerFactory.getLogger(Boss.class);

    public static void main(String[] args) throws InterruptedException {
        Properties properties = ParameterUtil.fromArgument(args);
        String path = properties.getProperty(YAML_FILE_PATH);
        int nettyBossPort = Integer.parseInt(DataMockYamlReader.getValueAsString(path, NETTY_BOSS_PORT));
        // 初始化
        WorkerManager workerManager = new WorkerManager();
        RecordGeneratorManager recordGeneratorManager = new RecordGeneratorManager();
        MessageUtil.initMap(workerManager , recordGeneratorManager);
        ZookeeperManager zookeeperManager = new ZookeeperManager(workerManager , recordGeneratorManager);
        zookeeperManager.startBoss();
        ServerBootstrap server = new ServerBootstrap();
        ChannelFuture bind = server.group(new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new MessageDecoder());
                        ch.pipeline().addLast(new MessageEncoder());
                        ch.pipeline().addLast(new EventHandler());
                    }
                }).childOption(ChannelOption.RCVBUF_ALLOCATOR, new FixedRecvByteBufAllocator(10 * 1024))
                .childOption(ChannelOption.SO_RCVBUF, 10 * 1024)
                .bind(nettyBossPort);
        bind.sync();
        Channel channel = bind.channel();
    }
}
